# -*-coding:utf8-*-
# RouteChecker
# v0.0.1
# https://code.google.com/p/routechecker/
# GNU GPL v3
import urllib2,re
print "=================================================="
print "                 航路查询"
def getweatherinfo(icao):
	metarurl="http://www.flightsimaviation.com/db/airports/"+icao.upper()
	req=urllib2.Request(metarurl)
	metarsource=urllib2.urlopen(req).read()
	metar=re.search("<(\/?\w+)[^>]*>\w[A-Z:]{5}<(\/?\w+)[^>]*>\W[A-Z0-9-\s\/]+",metarsource)
	metarinfo=metar.group()
	print metarinfo.replace("<b>METAR:</b> ","")

while True:
    leavingicao=raw_input("请输入出发机场的ICAO代码：")
    arrivalicao=raw_input("请输入目的地机场的ICAO代码:")
    if len(leavingicao) <> 4 or len(arrivalicao) <> 4:
        print "ICAO代码有误或未输入，请重试！"
        print "-----------------------------------------------------"
        continue
    else:
        urlstring="http://www.vaocs.net/info/index.php?id1="+leavingicao+"&sele1=&id2="+arrivalicao+"&sele2=&rand=0&inputrte="
        req=urllib2.Request(urlstring)
        source=urllib2.urlopen(req).read()
        if source.find("无航路结果")==0:
            print "无航路结果!"
            break
        if source.find("机场代码未找到!")==0:
            print "机场代码未找到!"
            break
        routesource=re.search("<(\/?\w+)[^>]*>\W{6,80}\w[A-Z0-9\s]+<(\/?\w+)[^>]*>\W{6,80}\w[A-Z0-9\s]+<(\/?\w+)[^>]*>",source)
        realroute=re.search("<b>\W{6,80}\w[A-Z0-9\s]+",routesource.group())
        leavingroute=re.search("<br>\W{6,80}\w[A-Z0-9\s]+",routesource.group())
        timeinfo=re.search("<tt>\W{10}\D+\d+\D+\d+\D+\d+\D+\d+\D+\d+<\/b>\W+<br>\W{12}",source)
        levelinfo=re.search("<br>\W+\w[A-Za-z0-9\s]+\W+\w[A-Z0-9>()\W\s\/]+<\/b>",source)
        realroutefix=realroute.group()
        leavingroutefix=unicode(leavingroute.group(),"utf8")
        realroutefix=realroutefix.replace("<b>","")
        leavingroutefix=leavingroutefix.replace("<br>","")
        timeinfofix=timeinfo.group()
        levelinfofix=levelinfo.group()
        replacegroup=("<tt>","</tt>","<br>","<b>","</b>")
        levelreplacegroup=("<br>","</b>","<b>")
        for i in replacegroup:
            timeinfofix=timeinfofix.replace(i,"")
        for i in levelreplacegroup:
            levelinfofix=levelinfofix.replace(i,"")
        print "-----------------------------------------------------"
        print unicode(realroutefix,"utf8")
        print ""
        print leavingroutefix
        print ""
        print "时间信息:",unicode(timeinfofix,"utf8")
        print ""
        print "高度层信息:",unicode(levelinfofix,"utf8")
        print ""
        print "气象报文"
        getweatherinfo(leavingicao)
        getweatherinfo(arrivalicao)
        print "======================================================"
        break
